<template>
  <div>
    <!-- 导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片主题内容 -->
    <el-card>
      <!-- 消息提示 -->
      <el-alert title="添加商品信息" type="info" show-icon center></el-alert>
      <!-- 步骤条 -->
      <el-steps :active="activeIndex-0" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 左侧标签进度条 -->
      <el-form
        :model="addGoodsForm"
        :rules="addGoodsRules"
        ref="addGoodsFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          tabPosition="left"
          v-model="activeIndex"
          :before-leave="beforeLeave"
          @tab-click="changeTab"
        >
          <el-tab-pane label="基本信息" name="0">
            <!-- 表单 -->
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addGoodsForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addGoodsForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addGoodsForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addGoodsForm.goods_cat"
                expand-trigger="hover"
                :options="goodsList"
                :props="goodsListProps"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in paramsList" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :label="Citem"
                  v-for="(Citem,Cindex) in item.attr_vals"
                  :key="Cindex"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="(item,index) in getGoodsAttrList"
              :key="index"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addGoodsForm.goods_introduce" />
            <el-button type="primary" @click="btnAdd">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 点击放大图片 -->
    <el-dialog title="图片预览" :visible.sync="previewDialogVisible" width="50%">
      <span>
        <img :src="bigPic" alt class="previewImg" />
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 导入深拷贝包
import _ from 'lodash'
export default {
  data() {
    return {
      // 商品分类列表
      goodsList: [],
      goodsListProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
      },
      // 索引条激活的选项
      activeIndex: '0',
      addGoodsForm: {
        // 商品名称
        goods_name: '',
        // 价格
        goods_price: '0',
        // 重量
        goods_weight: '0',
        goods_number: '0',
        goods_cat: [],
        pics: [],
        // 商品介绍
        goods_introduce: '',
        attrs: []
      },
      // 表单验证规则
      addGoodsRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' },
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
        ],
      },
      // 分类参数数据
      paramsList: [],
      // 商品属性数据
      getGoodsAttrList: [],
      // 上传图片的请求头
      headerObj: {
        Authorization: window.sessionStorage.getItem('token'),
      },
      bigPic: '',
      previewDialogVisible: false,
    }
  },
  methods: {
    // 商品分类书
    async getGoodsClass() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.$message.success('获取成功')
      this.goodsList = res.data
    },

    // 标签页的切换
    beforeLeave(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addGoodsForm.goods_cat.length !== 3) {
        this.$message.error('请选择参数名称')
        return false
      }
    },
    // 获取商品分类数据
    async changeTab() {
      if (this.activeIndex == '1') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'many' },
          }
        )
        if (res.meta.status !== 200) return this.$message.error('获取失败')
        res.data.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.paramsList = res.data
      }
      // 获取商品属性的列表
      if (this.activeIndex == '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'only' },
          }
        )
        if (res.meta.status !== 200) return this.$message.error('获取失败')
        this.getGoodsAttrList = res.data
      }
    },
    // 点击查看放大图片
    handlePreview(file) {
      this.bigPic = file.response.data.url
      this.previewDialogVisible = true
    },
    // 移出图片
    handleRemove(file) {
      const filePath = file.response.data.tmp_path
      const i = this.addGoodsForm.pics.findIndex((x) => x.pic === filePath)
      this.addGoodsForm.pics.splice(i, 1)
    },
    // 图片上传成功
    handleSuccess(response) {
      const infoPic = { pic: response.data.tmp_path }
      this.addGoodsForm.pics.push(infoPic)
    },

    // 确认添加表单预校验
    btnAdd() {
      this.$refs.addGoodsFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请填写必要的表单项')
        }
        // 进行添加，但是需要对good_cat转换行以，分割的字符串
        // 需要对addGoodsForm进行深拷贝lodash cloneDeep
        const form = _.cloneDeep(this.addGoodsForm)
        form.goods_cat = form.goods_cat.join(',')

        //处理商品参数   和处理商品属性
        this.paramsList.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' '),
          }
          this.addGoodsForm.attrs.push(newInfo)
        })

        this.getGoodsAttrList.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          }
          this.addGoodsForm.attrs.push(newInfo)
        })
        form.attrs = this.addGoodsForm.attrs
        // 发起添加请求
        // 商品的名称必须是唯一的
        const {data:res} = await this.$http.post('goods',form)
        if(res.meta.status!==201) return this.$message.error(res.meta.msg)
        this.$message.success('添加成功')
        this.$router.push('/goods')
      })
    },
  },
  computed: {
    cateId() {
      if (this.addGoodsForm.goods_cat.length === 3) {
        return this.addGoodsForm.goods_cat[2]
      }
      return null
    },
  },
  created() {
    this.getGoodsClass()
  },
}
</script>

<style lang="less" scoped>
.el-steps {
  margin-top: 20px;
}
.el-checkbox {
  margin: 0 5px 0 0 !important;
}
.previewImg {
  width: 100%;
}
.el-button {
  margin-top: 10px;
}
</style>